#!/usr/bin/env python
# -*- coding: utf-8 -*-

import flask
import json
import operator
import os
import time
import sys

import additional
import connections
import parsing

from flask import Flask, render_template, send_from_directory
from flask.ext import restful
from flask.ext.restful import reqparse, abort, Api, Resource
from flask.ext.sqlalchemy import SQLAlchemy

from files import open_file, open_json, save_file, save_json
from parsing import term

# Remember to make it false before pushing on heroku!!!
DEBUG = False
TESTING = False
UPLOAD_FOLDER = 'temp'

app = Flask(__name__)
api = restful.Api(app)

# Next line is used for debugging on local copy.
# app.config.from_object('plik')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
db = SQLAlchemy(app)

parser = reqparse.RequestParser()
parser.add_argument('task', type=str, help='Task Parsing Error')
# parser.add_argument('nr', type=int, help='Number Parsing Error')

class JsonFiles(db.Model):
    json_name = db.Column(db.String(50), primary_key=True, unique=True)
    json_string = db.Column(db.Text)

    def __init__(self, name, j_string):
        self.json_name = name
        self.json_string = j_string

    def __repr__(self):
        return '<JSONFile %s>' % (self.json_name.encode(sys.stdout.encoding))

class Versions(db.Model):
    ver_name = db.Column(db.String(10), primary_key=True, unique=True)
    ver_version = db.Column(db.String(50))

    def __init__(self, name, version):
        self.ver_name = name
        self.ver_version = version

    def __repr__(self):
        return '<Version of %s - %s>' % (self.ver_name.encode(sys.stdout.encoding),
          self.ver_version.encode(sys.stdout.encoding))

def send_json_to_database(new, n_ver, j_name):
    old = JsonFiles.query.get(j_name + ".json")
    if old != None:
        db.session.delete(old)
        db.session.commit()
    new_v = Versions(j_name, n_ver)
    db.session.add(new_v)
    new_j = JsonFiles(j_name + ".json", json.JSONEncoder().encode(new))
    db.session.add(new_j)
    db.session.commit()
    return

def update_employees():
    (lista, empl_ver) = parsing.parse_worker_list()
    to_del = Versions.query.get("empl_list")
    if to_del != None:
        if (to_del.ver_version != empl_ver):
            db.session.delete(to_del)
            db.session.commit()
        else:
            return
    send_json_to_database(lista, empl_ver, "empl_list")
    return

def update_schedule():
    # TODO: Check is it Winter or Summer term.
    act_term = term.SUMMER
    (schedule, sch_ver) = parsing.parse_schedule(act_term)
    to_del = Versions.query.get("schedule")
    if to_del != None:
        if (to_del.ver_version != sch_ver):
            db.session.delete(to_del)
            db.session.commit()
        else:
            return
    send_json_to_database(schedule, sch_ver, "schedule")
    return

def update_news():
    (news, n_ver) = parsing.parse_news()
    to_del = Versions.query.get("news")
    if to_del != None:
        if (to_del.ver_version != n_ver):
            db.session.delete(to_del)
            db.session.commit()
        else:
            return
    send_json_to_database(news, n_ver, "news")
    return

def update_all_things():
    print "0% - Main Update:"
    update_employees()
    print "33% - Employees done!"
    update_schedule()
    print "67% - Schedule done!"
    update_news()
    print "100% - News done!"
    return

class MainPage(restful.Resource):
    def post(self):
        args = parser.parse_args()
        if args['task'] is not None:
            if (args['task'] == "update"):
                update_all_things()
                return {'It\'s': 'done!'}
            elif (args['task'] == "up_empl"):
                update_empl_file()
                return {'It\'s': 'done!'}
            elif (args['task'] == "up_sche"):
                update_schedule()
                return {'It\'s': 'done!'}
            elif (args['task'] == "up_news"):
                update_news()
                return {'It\'s': 'done!'}
            else:
                return {'Wrong': 'task!'}
        return {'None': 'task?'}

api.add_resource(MainPage, '/')

class VersionsPage(restful.Resource):
    def get(self):
        lista = Versions.query.all()
        ret_val = dict()
        for data_v in lista:
            ret_val[data_v.ver_name] = data_v.ver_version
        return ret_val

api.add_resource(VersionsPage, '/versions/')

class EmployeesPage(restful.Resource):
    def get(self):
        empl_list = JsonFiles.query.get("empl_list.json")
        return empl_list.json_string

api.add_resource(EmployeesPage, '/empl_list/')

class SchedulePage(restful.Resource):
    def get(self):
        sche = JsonFiles.query.get("schedule.json")
        return sche.json_string

api.add_resource(SchedulePage, '/schedule/')

class NewsPage(restful.Resource):
    def get(self):
        news = JsonFiles.query.get("news.json")
        return news.json_string

api.add_resource(NewsPage, '/news/')

@app.route('/')
def main_page():
    error = None
    return render_template('main.html', error=error)

@app.route('/WMIMobile.apk')
def application_download():
    return send_from_directory(app.config['UPLOAD_FOLDER'], "WMIMobile.apk")

@app.route('/api_doc/')
@app.route('/help/')
def api_documentation():
    error = None
    return render_template('help.html', error=error)

# app start
if __name__ == '__main__':
    app.debug=DEBUG
    app.run(host='0.0.0.0')